Page({
  data: {
    avatarUrl: '',          // 头像路径
    name: '',               // 姓名
    gender: '',             // 性别
    birthday: '',           // 出生年月
    school: '',              // 学校
    major: '',               // 专业
    gpa: '',                 // 绩点
    ranking: '',            // 排名
    researchExp: '',        // 科研经历
    competitionExp: '',     // 竞赛经历
    internshipExp: '',      // 实习经历
    futurePlan: ''           // 未来意向
  },
  fieldMapping: {
    name: 'name',
    gender: 'sex',
    school: 'university',
    major: 'major',
    gpa: 'gpa',
    ranking: 'rank',
    researchExp: 'sci_exp',
    competitionExp: 'comp_exp',
    internshipExp: 'prac_exp',
    futurePlan: 'willness',
    birthday: 'birthdate'
  },
  // 选择头像
  chooseAvatar(e) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        this.setData({
          avatarUrl: res.tempFiles[0].tempFilePath
        })
      }
    })
  },

  // 表单输入处理
  handleInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [field]: e.detail.value
    })
  },

  // 日期选择
  handleDateChange(e) {
    this.setData({
      birthday: e.detail.value
    })
  },

  // 提交表单
  submitForm() {
    if (!this.validateForm()) return
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo.userid;
    const params = {
      "name": this.data.name,
      "sex": this.data.gender,
      "university": this.data.school,
      "major": this.data.major,
      "gpa": parseInt(this.data.gpa),
      "rank": this.data.ranking,
      "sci_exp": this.data.researchExp,
      "comp_exp": this.data.competitionExp,
      "prac_exp":this.data.internshipExp,
      "willness":this.data.futurePlan,
      "birthdate":this.data.birthday
    }
    console.log(params);
    wx.request({
      url: 'https://pszap.top/base/'+userId,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: params,
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存到全局数据
          const app = getApp();
          app.globalData.userInfo = params;
          wx.setStorageSync('userInfoData', params);
          wx.showToast({ title: '保存成功' });
        } else {
          wx.showToast({ title: res.data.msg || '保存失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络连接失败', icon: 'none' });
      }
    })
    
  },

  // 表单验证
  validateForm() {
    const requiredFields = [
      { field: 'name', name: '姓名' },
      { field: 'gender', name: '性别' },
      { field: 'birthday', name: '出生年月' }
    ]

    for (let item of requiredFields) {
      if (!this.data[item.field]) {
        wx.showToast({
          title: `请填写${item.name}`,
          icon: 'none'
        })
        return false
      }
    }
    return true
  },

  // 加载已保存数据
  onLoad() {
    const savedData = wx.getStorageSync('userInfoData') || {};
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.userid) {
        this.setData({ ...savedData });
        return;
    }
    const userId = userInfo.userid;
    
    // 添加加载状态提示
    wx.showLoading({ title: '加载中...' });
    
    // 从后端加载数据
    wx.request({
        url: 'https://pszap.top/base/' + userId,
        method: 'GET',
        timeout: 5000, // 设置超时时间
        header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
            wx.hideLoading();
            if (res.statusCode === 200 && res.data) {
                const remoteData = this.mapServerToLocal(res.data);
                this.setData({ 
                    ...savedData,
                    ...remoteData 
                });
            } else {
                // 处理其他状态码
                console.warn('获取数据失败:', res.statusCode);
                this.setData({ ...savedData });
            }
        },
        fail: (err) => {
            wx.hideLoading();
            console.error('请求失败:', err);
            // 使用本地缓存数据作为回退
            this.setData({ ...savedData });
            wx.showToast({
                title: '数据加载失败',
                icon: 'none'
            });
        }
    });
},

// 新增后端字段到前端字段的映射方法
mapServerToLocal(serverData) {
    const localData = {};
    Object.keys(this.fieldMapping).forEach(localKey => {
        const serverKey = this.fieldMapping[localKey];
        if (serverData[serverKey] !== undefined) {
            localData[localKey] = serverData[serverKey];
        }
    });
    return localData;
}
})